﻿using System.Collections.Generic;
using Runtime.CoreAttribute;
using Runtime.Common.Interface;
using UnityEngine;

namespace Runtime.DesignPattern
{
    public class SingletonRegister
    {
        public static Dictionary<string, IGameSingleton> dict = new();

        public static void Register(IGameSingleton singleton)
        {
            dict.Add(singleton.Id.ToString(), singleton);
            Debug.LogError($"创建单例总数：{dict.Count}");
        }

        public static void Unregister(IGameSingleton singleton)
        {
            var k = singleton.Id.ToString();
            dict.Remove(k);
        }

        public static void Destroy()
        {
            dict.Clear();
        }

        public static void ClearSingleton()
        {
            foreach (var singleton in dict.Values)
            {
                singleton.Destroy();
            }
            Destroy();
        }

        [StaticObjectRestoreMothed]
        private static void restore()
        {
            List<string> infos = new();
            foreach (var single in dict.Values)
            {
                infos.Add( $"{single.Id}-->{single.GetType()}");
            }
            Debug.LogWarning("还原所有单例，" +
                           $"{string.Join("=>",infos)}-->" +
                           $"count:{dict.Count}");
            ClearSingleton();
        }
    }
}